import React, { PropsWithChildren } from 'react';
import { Form, message } from 'antd';
import {
  ModalForm,
  ProFormText,
  ProFormTreeSelect,
} from '@ant-design/pro-components';
import { roleV1AdminControllerUpdate, roleV1AdminControllerCreate } from '@/services/auto/roleAdmin';
import { resourceV1AdminControllerAll } from '@/services/auto/resourceAdmin';

interface FormData extends API.RoleAdminCreateDto {
}

interface Props {
  data?: API.RoleAdminAllResult;
  reload?: () => void;
}

export default (props: PropsWithChildren<Props>) => {
  const { data, reload, children } = props;

  const [form] = Form.useForm<FormData>();

  return (
    <ModalForm
      layout="horizontal"
      width={400}
      labelCol={{style: {width: 100}}}
      modalProps={{
        maskClosable: false,
      }}
      form={form}
      onOpenChange={(val) => {
        if (val) {
          if (data?.uuid) {
            form.setFieldsValue({
              ...data,
            });
          }
        } else {
          form.resetFields();
        }
      }}
      title={data?.uuid ? '编辑角色' : '添加角色'}
      trigger={children as JSX.Element}
      onFinish={(values) => {
        let service;
        const newValues: API.RoleAdminCreateDto = {
          ...values,
        };
        if (data?.uuid) {
          service = roleV1AdminControllerUpdate({uuid: data.uuid}, newValues);
        } else {
          service = roleV1AdminControllerCreate(newValues);
        }
        return service
          .then(() => {
            message.success('操作成功');
            reload?.();
            return true;
          })
          .catch(() => {
            return false;
          });
      }}
    >
      <ProFormText
        name="name"
        label="角色名"
        rules={[{ required: true, message: '请输入 角色名' }]}
        fieldProps={{
          maxLength: 50,
        }}
      />
      <ProFormText
        name="desc"
        label="角色描述"
        fieldProps={{
          maxLength: 50,
        }}
      />
      <ProFormTreeSelect
        name="resourceUuids"
        label="角色权限"
        allowClear
        secondary
        request={()=>{
          return resourceV1AdminControllerAll();
        }}
        fieldProps={{
          filterTreeNode: true,
          showSearch: true,
          multiple: true,
          treeNodeFilterProp: 'name',
          treeDataSimpleMode: {
            id: 'uuid',
            pId: 'parentUuid',
          },
          fieldNames: {
            label: 'name',
            value: 'uuid',
          },
          // treeCheckable: true,
          // showCheckedStrategy: TreeSelect.SHOW_ALL,
          // treeCheckStrictly: true,
        }}
      />
    </ModalForm>
  );
};
